package cn.edu.gdgm.system.controller;

import cn.edu.gdgm.system.dto.Result;
import cn.edu.gdgm.system.entity.HealthCard;
import cn.edu.gdgm.system.entity.User;
import cn.edu.gdgm.system.service.IHealthCardsService;
import cn.edu.gdgm.system.service.IUserService;
import cn.fightingguys.security.web.wechat.entity.WeChatMiniProgramUserDetails;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;

/**
 * @author quan
 * @date 2021-03-06
 */
@Api(tags = {"健康卡Controller"})
@RestController
@RequestMapping("/healthCard")
public class HealthCardController {
    private Logger log = LoggerFactory.getLogger(getClass());
    @Resource
    private IHealthCardsService healthCardsService;

    @Resource
    private IUserService userService;

    @PostMapping()
    @ApiOperation(value = "保存健康卡数据")
    @PreAuthorize("hasAuthority('Verified')")
    public Result add(HealthCard healthCard) {
        return toResult(healthCardsService.saveOrUpdate(healthCard));
    }

    @GetMapping()
    @PreAuthorize("hasAuthority('Verified')")
    @ApiOperation(value = "查看当前用户健康卡数据")
    public Result findOne(@ApiIgnore @AuthenticationPrincipal WeChatMiniProgramUserDetails userDetails) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("wechat_open_id", userDetails.getOpenId());
        User one = userService.getOne(queryWrapper);
        String id = one.getId();
        if (StringUtils.isBlank(id)) {
            return Result.error(202, "用户不存在");
        }
        HealthCard healthCard = healthCardsService.getById(id);
        return Result.success(healthCard);
    }



    private Result toResult(boolean b) {
        if (b) {
            return Result.success("操作成功");
        } else {
            return Result.error(201, "操作失败");
        }
    }
}
